//
//  FMDBHelper.m
//  Qian
//
//  Created by 周博 on 17/2/13.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "FMDBHelper.h"

#define kId @"id"
#define kContent @"content"
#define kTableName @"notiTable"
#define kSqlName @"notiSql"

static FMDBHelper *fmManager = nil;

@interface FMDBHelper ()
{
    
}

@end

@implementation FMDBHelper

+ (FMDBHelper *)fmManger{
    if (!fmManager) {
        fmManager = [[FMDBHelper allocWithZone:NULL] init];
    }
    return fmManager;
}

- (void)getFMDBBySQLName:(NSString *)sqlName{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    database_path = [documents stringByAppendingPathComponent:sqlName];
    
    db = [FMDatabase databaseWithPath:database_path];
}

#pragma mark - 创建用户表

- (void)createTable
{
    [self getFMDBBySQLName:kSqlName];
    
    //sql 语句
    if ([db open]) {
        NSString *sqlCreateTable =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT)",kTableName,kId,kContent];
        BOOL res = [db executeUpdate:sqlCreateTable];
        if (!res) {
            NSLog(@"error when creating db table");
        } else {
            NSLog(@"success to creating db table");
        }
        [db close];
        
    }
}



-(void)insertMyUserInfoDataByContent:(NSString *)content
{
    if ([db open]) {
        BOOL flag = [db executeUpdate:@"insert into notiTable (content) values(?)",content];

        if (!flag) {
            NSLog(@"error when insert db table");
        } else {
            NSLog(@"success to insert db table");
        }
        [db close];
    }
    
}


-(NSMutableArray *)selectData
{
    NSMutableArray *array = [NSMutableArray array];
    if ([db open]) {
        NSString * sql = [NSString stringWithFormat:
                          @"SELECT * FROM %@ ORDER BY id desc",kTableName];
        FMResultSet * rs = [db executeQuery:sql];
        while ([rs next]) {

            NSString *contentString = [rs stringForColumn:kContent];
            [array addObject:contentString];

        }
        [db close];
    }
    return array;
}

-(NSMutableArray *)selectDataById:(NSString *)countId
{
    NSMutableArray *array = [NSMutableArray array];
    if ([db open]) {
        NSString * sql = [NSString stringWithFormat:
                          @"SELECT * FROM %@ where id = %@",kTableName,countId];
        FMResultSet * rs = [db executeQuery:sql];
        while ([rs next]) {
            
            NSString *contentString = [rs stringForColumn:kContent];
            [array addObject:contentString];
            
        }
        [db close];
    }
    return array;
}
@end
